package com.huiyujiaoyu.powertime.ui.home;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.huiyujiaoyu.base.BaseActivity;
import com.huiyujiaoyu.http.HttpApi;
import com.huiyujiaoyu.http.HttpMethods;
import com.huiyujiaoyu.powertime.R;
import com.huiyujiaoyu.powertime.model.IndexItemModel;
import com.huiyujiaoyu.powertime.model.SimpleBean;
import com.huiyujiaoyu.powertime.model.SimpleListBean;
import com.huiyujiaoyu.powertime.model.TabEntity;
import com.huiyujiaoyu.powertime.model.UserInfoBean;
import com.huiyujiaoyu.util.ActivityUtil;
import com.huiyujiaoyu.util.AudioPlayer;
import com.huiyujiaoyu.util.Constant;
import com.huiyujiaoyu.util.DialogUtil;
import com.huiyujiaoyu.util.GlideUtil;
import com.huiyujiaoyu.util.StringUtils;
import com.huiyujiaoyu.widget.Remind2Dialog;
import com.huiyujiaoyu.widget.RemindDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

import static com.huiyujiaoyu.util.StringUtils.getFullUrl;


/**
 * Created by win7 on 2017/6/17.
 * 更多热门文章界面
 */

public class ShiPinDetailActivity extends BaseActivity {
    @BindView(R.id.videoplayer)
    JCVideoPlayerStandard mVideoplayer;
    @BindView(R.id.tv_play_count)
    TextView mTvPlayCount;
    @BindView(R.id.iv_save)
    ImageView mIvSave;
    @BindView(R.id.iv_share)
    ImageView mIvShare;
    @BindView(R.id.rl_playvoice)
    RelativeLayout mRlPlayvoice;
    @BindView(R.id.tab)
    CommonTabLayout mTab;
    @BindView(R.id.tv_jianjie)
    TextView mTvJianjie;
    @BindView(R.id.tv_desce)
    TextView mTvDesce;
    @BindView(R.id.ll_jianjie)
    LinearLayout mLlJianjie;
    @BindView(R.id.fl_zhangjie)
    FrameLayout mFlZhangjie;
    @BindView(R.id.zhangjie)
    RecyclerView mZhangjie;
    @BindView(R.id.ibtn_comment)
    ImageButton mIbtnComment;
    @BindView(R.id.fl_pinglun)
    FrameLayout mFlPinglun;
    @BindView(R.id.comment)
    RecyclerView mComment;
    @BindView(R.id.ll_wudpinglun)
    FrameLayout mLlWudpinglun;
    @BindView(R.id.iv_icon)
    ImageView mIvIcon;
    @BindView(R.id.tv_dingyue)
    TextView mTvDingyue;
    @BindView(R.id.tv_author_name)
    TextView mTvAuthorName;
    @BindView(R.id.tv_dingyueshu)
    TextView mTvDingyueshu;
    @BindView(R.id.rl_detail)
    RelativeLayout mRlDetail;
    @BindView(R.id.nsv_content)
    NestedScrollView nsv_content;

    private ArrayList<String> datas;


    private List<IndexItemModel> zjdatas, pldatas;
    private BaseQuickAdapter<IndexItemModel, BaseViewHolder> zjadapter, pladapter;
    private String content_id, chapter_id, voiceurl,coverurl;

    private boolean isOnclick;

    private RemindDialog loginDialog, dingyueDialog;
    private Remind2Dialog remindDialog;
    private boolean isPay, isOrder;

    public static void launch(Context mContext, String content_id){
        Bundle  b = new Bundle();
        b.putString(Constant.DATA,content_id);
        ActivityUtil.startActivity(mContext,ShiPinDetailActivity.class,b);
    }

    public void initView() {

    }

    public void initData() {
        datas = new ArrayList<>();
        datas.add("简介");
        datas.add("章节");
        datas.add("评论");
        ArrayList<CustomTabEntity> customTabEntities = new ArrayList<>();
        for (int i = 0; i < datas.size(); i++) {
            customTabEntities.add(new TabEntity(datas.get(i)));
        }
        mTab.setTabData(customTabEntities);
        mTab.setCurrentTab(0);
        content_id = getIntent().getStringExtra(Constant.DATA);
        HttpMethods.getInstance().view(mContext, getComp(), this, content_id, "0", Constant.CONTENT_TYPE_SP);
        zjdatas = new ArrayList<>();
        pldatas = new ArrayList<>();
        zjadapter = new BaseQuickAdapter<IndexItemModel, BaseViewHolder>(R.layout.cell_video_zhangjie, zjdatas) {
            @Override
            protected void convert(BaseViewHolder helper, IndexItemModel item) {
                GlideUtil.loadImg((ImageView) helper.getView(R.id.iv_pic), getFullUrl(item.cover));
                helper.setText(R.id.tv_title, "第" + (helper.getAdapterPosition() + 1) + "章");
                helper.setText(R.id.tv_desc, item.title);
            }
        };
        pladapter = new BaseQuickAdapter<IndexItemModel, BaseViewHolder>(R.layout.cell_headling_comment, zjdatas) {
            @Override
            protected void convert(BaseViewHolder helper, IndexItemModel item) {
                GlideUtil.loadCircleImg((ImageView) helper.getView(R.id.cir_icon), getFullUrl(item.photo));
                helper.setText(R.id.tv_title, item.name)
                        .setText(R.id.tv_date, item.created_at)
                        .setText(R.id.tv_content, item.content);
            }
        };
        mZhangjie.setLayoutManager(new LinearLayoutManager(mContext));
        mComment.setLayoutManager(new LinearLayoutManager(mContext));
        mZhangjie.setAdapter(zjadapter);
        mComment.setAdapter(pladapter);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                isOnclick = true;
                selecteStatus(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        nsv_content.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int y, int oldScrollX, int oldScrollY) {
                int positionPx2 = mFlZhangjie.getTop() - mFlZhangjie.getHeight();
                int positionpx3 = mFlPinglun.getTop() - mFlPinglun.getHeight();

                if (!isOnclick) {
                    if (y >= 0 && y < positionPx2) {
                        mTab.setCurrentTab(0);
                    } else if (y >= positionPx2 && y < positionpx3) {
                        mTab.setCurrentTab(1);
                    } else if (y >= positionpx3) {
                        mTab.setCurrentTab(2);
                    }
                }
            }
        });

        nsv_content.setOnTouchListener(new View.OnTouchListener() {

            private int lastY = 0;
            private int touchEventId = -9983761;
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    View scroller = (View) msg.obj;
                    if (msg.what == touchEventId) {
                        if (lastY == scroller.getScrollY()) {
                            handleStop(scroller);
                        } else {
                            handler.sendMessageDelayed(handler.obtainMessage(touchEventId, scroller), 5);
                            lastY = scroller.getScrollY();
                        }
                    }
                }
            };

            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    handler.sendMessageDelayed(handler.obtainMessage(touchEventId, v), 5);
                }
                return false;
            }

            private void handleStop(Object view) {
                isOnclick = false;
            }
        });


        mZhangjie.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle b = new Bundle();
                b.putString(Constant.DATA, zjdatas.get(position).content_id + "");
                ActivityUtil.startActivity(mContext, ShiPinDetailActivity.class, b);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shipin;
    }

    //设置数据
    private void setUpColumnData(IndexItemModel columnData) {

        if (columnData == null) {
            return;
        }
        GlideUtil.loadImg(mIvIcon, getFullUrl(columnData.cover));
        mTvAuthorName.setText(columnData.title);
        mTvDingyueshu.setText(columnData.subscribers + "人订阅");
        coverurl = columnData.cover;

    }

    private void setUpContentData(IndexItemModel contentData) {

        if (contentData == null) {
            return;
        }
        mTvJianjie.setText(contentData.title);
        mTvDesce.setText(contentData.content);
        mTvPlayCount.setText(contentData.view_count + "次");
        voiceurl = contentData.access_url;
        //章节
        if (contentData.chapter_count > 0) {
            HttpMethods.getInstance().chapters(mContext, getComp(), this, content_id, "0");
        }
        //评论
        if (contentData.comment_count > 0) {
            HttpMethods.getInstance().cIndex(mContext, getComp(), this, content_id, contentData.column_id + "", "0", 1);
        }
        initShiPin();
    }

    SimpleBean dataModel;

    @Override
    public void onNext(Object o, int httpcode) {
        super.onNext(o, httpcode);
        switch (httpcode) {
            case HttpApi.HTTP_VIEW:
                dataModel = (SimpleBean) o;
                setUpColumnData(dataModel.column);
                setUpContentData(dataModel.content);
                //收藏
                mIvSave.setSelected("1".equals(dataModel.collected));
                //订阅
                isOrder = "1".equals(dataModel.subscribed);
                mTvDingyue.setText(isOrder ? "已订阅" : "订阅");
                //是否免费
                isPay = 1 == dataModel.status;
                //评论
                break;
            case HttpApi.HTTP_CHAPTERS:
                zjdatas.addAll(((List<IndexItemModel>) o));
                zjadapter.notifyDataSetChanged();
                break;
            case HttpApi.HTTP_COMMENT_INDEX:
                pldatas.addAll(((SimpleListBean) o).list);
                pladapter.notifyDataSetChanged();
                break;
        }
    }


    public void initShiPin(){
        mVideoplayer = (JCVideoPlayerStandard) findViewById(R.id.videoplayer);
        mVideoplayer.setUp(voiceurl, JCVideoPlayerStandard.SCREEN_LAYOUT_NORMAL, "");
        GlideUtil.loadImg(mVideoplayer.thumbImageView, StringUtils.getFullUrl(coverurl));


    }

    /**
     * 根据选的类型 跳转到指定的位置
     */
    private void selecteStatus(int position) {
        int px = 0;
        switch (position) {
            case 0: //简介位置
                break;
            case 1: //章节位置
                px = mFlZhangjie.getTop() - mFlZhangjie.getHeight();
                break;
            case 2: //评论位置
                px = mFlPinglun.getTop() - mFlPinglun.getHeight();
                break;
        }
        scrolltoPosition(px);

    }


    //让scrollView滚动到指定的位置
    private void scrolltoPosition(int position) {
        nsv_content.smoothScrollTo(0, position);
    }


    @OnClick({R.id.ll_save, R.id.ll_share, R.id.tv_dingyue, R.id.ibtn_comment, R.id.ibtn_back_2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_save:
                if (dataModel != null) {
                    if (!UserInfoBean.getInstance().isLogin()) {
                        if (loginDialog == null) {
                            loginDialog = DialogUtil.getLoginDialog(mContext);
                        }
                        DialogUtil.showDialog(loginDialog);
                    } else {
                        HttpMethods.getInstance().collect(mContext, getComp(), this, content_id);
                    }
                }
                break;
            case R.id.ll_share:
                break;
            case R.id.tv_dingyue:
                // SubscribeDetailsActivity.launch(this);
                break;
            case R.id.ibtn_comment:
                //EditCommentActivity.launch(mContext);
                break;
            case R.id.ibtn_back:
                onBackPressed();
                break;
            case R.id.ibtn_share:
                break;
            case R.id.ibtn_back_2:
                onBackPressed();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }
}
